<template>
  <div>
    <el-card>
      <h1>在线考试</h1>
      <el-select
        v-model="filterForm.examType"
        clearable
        placeholder="Select"
        style="width: 240px"
      >
        <el-option label="全部" value="" @click="getNewExamInfo('')"></el-option>
        <el-option label="完全开放" value="1" @click="getNewExamInfo('1')"></el-option>
        <el-option label="需要密码" value="2" @click="getNewExamInfo('2')"></el-option>
      </el-select>
      <el-table :data="paginatedExamInfo" stripe style="width: 100%">
        <el-table-column prop="examId" label="考试ID" width="180" />
        <el-table-column prop="examName" label="考试名称" width="180" />
        <el-table-column prop="typeText" label="考试类型" width="180" />
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="duration" label="时长" width="120" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              :disabled="scope.row.isDisabled"
              @click="showExamDetails(scope.row)"
            >
              {{ scope.row.buttonText }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      title="考试详情"
      v-model:visible="dialogVisible"
      width="50%"
      @close="clearExamDetails"
    >
      <el-card class="exam-details-card" :body-style="{ padding: '20px' }">
        <div>
          <p><strong>考试ID：</strong>{{ examDetails.examId }}</p>
          <el-divider></el-divider>
          <p><strong>考试名称：</strong>{{ examDetails.examName }}</p>
          <el-divider></el-divider>
          <p><strong>考试描述：</strong>{{ examDetails.examDesc }}</p>
          <el-divider></el-divider>
          <p><strong>考试时长：</strong>{{ examDetails.duration }} 分钟</p>
          <el-divider></el-divider>
          <p><strong>试卷总分：</strong>{{ examDetails.totalScore }}</p>
          <el-divider></el-divider>
          <p><strong>及格分数：</strong>{{ examDetails.passScore }}</p>
          <el-divider></el-divider>
          <p><strong>考试类型：</strong>{{ examDetails.typeText }}</p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="goToExam(examDetails.examId)">
            前往考试
          </el-button>
        </span>
      </el-card>
    </el-dialog>

    <div class="demo-pagination-block">
      <div class="demonstration">分页</div>
      <el-pagination
        v-model:current-page="state.page.pageNum"
        v-model:page-size="state.page.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="state.page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import type { ComponentSize } from 'element-plus'
import { getExamOnlineList } from '@/api/ExamOnline/Examonline'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()
const size = ref<ComponentSize>('default')
const background = ref(false)
const dialogVisible = ref(false)
const examDetails = reactive({
  examId: '',
  examName: '',
  examDesc: '',
  duration: 0,
  totalScore: 0,
  passScore: 0,
  typeText: '',
})
const state = reactive({
  ExamInfo: [],
  page: {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  },
})
const filterForm = reactive({
  examType: '', // 默认为空字符串
})

const paginatedExamInfo = computed(() => {
  const start = (state.page.pageNum - 1) * state.page.pageSize
  const end = state.page.pageNum * state.page.pageSize
  const now = new Date().getTime()

  return state.ExamInfo.slice(start, end).map((exam) => {
    const endTime = new Date(exam.endTime).getTime()
    const isDisabled = endTime <= now
    return {
      ...exam,
      typeText: exam.type === 1 ? '完全开放' : '需要密码',
      isDisabled,
      buttonText: isDisabled ? '暂不开放' : '前往考试',
    }
  })
})

async function getExamOnline(examType: string = '') {
  try {
    const { data } = await getExamOnlineList({
      examType,
      startTime: null,
      endTime: null,
      examName: null,
      pageNo: state.page.pageNum,
      pageSize: state.page.pageSize,
    })
    state.ExamInfo = data.data || []
    state.page.total = data.total || 0 // 确保从 API 获取到正确的总数
  } catch (error) {
    console.error('获取考试数据失败:', error)
  }
}

function handleExamTypeChange(value: string) {
  filterForm.examType = value
  getExamOnline(value) // 在选择考试类型时直接调用查询函数
}

function getNewExamInfo(value) {
  filterForm.examType = value
  getExamOnline(value)
}

function showExamDetails(exam) {
  examDetails.examId = exam.examId
  examDetails.examName = exam.examName
  examDetails.examDesc = exam.examDesc
  examDetails.duration = exam.duration
  examDetails.totalScore = exam.totalScore
  examDetails.passScore = exam.passScore
  examDetails.typeText = exam.type === 1 ? '完全开放' : '其他'
  dialogVisible.value = true
}

function clearExamDetails() {
  examDetails.examId = ''
  examDetails.examName = ''
  examDetails.examDesc = ''
  examDetails.duration = 0
  examDetails.totalScore = 0
  examDetails.passScore = 0
  examDetails.typeText = ''
}

function goToExam(examId) {
  if (examId) {
    router.push(`/exam/${examId}`)
  } else {
    ElMessage.error('无法获取考试ID')
  }
}

onMounted(() => {
  getExamOnline()
})

watch(() => filterForm.examType, () => {
  state.page.pageNum = 1
})

const handleSizeChange = (val: number) => {
  state.page.pageSize = val
  state.page.pageNum = 1
  getExamOnline(filterForm.examType) // 更新分页时也重新获取数据
}

const handleCurrentChange = (val: number) => {
  state.page.pageNum = val
  getExamOnline(filterForm.examType) // 更新当前页码时也重新获取数据
}
</script>

<style scoped lang="less">
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>